<?php

namespace App\Http\Middleware;

use App\Exceptions\BizException;
use App\Http\Requests\Request;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use App\Model\Agent as AgentModel;

class SubDomain
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        try{
            $host = $request->getHost();
            $hosts = explode('.', $host);
            if (isset($hosts[0]) && $hosts[0] == 'ytf')
                return redirect('newHome');
            if (empty($hosts[0]) || !is_numeric($hosts[0]))
                throw new BizException('网址错误');

            $agent_id = $hosts[0];
            $agent = AgentModel::where('id', $agent_id)->where('status', 1)->first();
            if (empty($agent))
                throw new BizException('店铺不存在或已冻结');

            $request->agent = $agent;
        } catch (BizException $e) {
            return response()->json(['status' => 0, 'info' => $e->getMessage()], 200, [], JSON_UNESCAPED_UNICODE);
        }

        return $next($request); 
    }
}
